<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="订单号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['production:orderPlan:add']">
              {{ $t('btn.add') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['production:orderPlan:edit']">
              {{ $t('btn.edit') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="single" @click="handleDelete" v-hasPermi="['production:orderplan:remove']">
              {{ $t('btn.delete') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['production:orderplan:import']">
              {{ $t('btn.import') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['production:orderplan:export']">
              {{ $t('btn.export') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="pointer" :disabled="single" @click="handleActivate" v-hasPermi="['production:orderplan:activate']">
              {{ $t('btn.activate') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="pointer" :disabled="single" @click="handleClosed" v-hasPermi="['production:orderplan:activate']">
              {{ $t('btn.closed') }}
            </el-button>
          </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="id" label="序号" align="center" v-if="columns.showColumn('id')"/>
      <el-table-column prop="lineCode" label="产线代号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('lineCode')"/>
      <el-table-column prop="orderType" label="订单类型" align="center" v-if="columns.showColumn('orderType')">
        <template #default="scope">
          <dict-tag :options=" options.orderTypeOptions" :value="scope.row.orderType"  />
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('orderCode')"/>
      <el-table-column prop="orderMaterial" label="订单物料" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('orderMaterial')"/>
      <el-table-column prop="productName" label="产品名称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('productName')"/>
      <el-table-column prop="productType" label="产品型号" align="center" v-if="columns.showColumn('productType')">
        <template #default="scope">
          <dict-tag :options=" options.productTypeOptions" :value="scope.row.productType"  />
        </template>
      </el-table-column>
      <el-table-column prop="onlineDate" label="上线日期" :show-overflow-tooltip="true"  v-if="columns.showColumn('onlineDate')"/>
      <el-table-column prop="offlineDate" label="下线日期" :show-overflow-tooltip="true"  v-if="columns.showColumn('offlineDate')"/>
      <el-table-column prop="orderRank" label="订单排序" align="center" v-if="columns.showColumn('orderRank')"/>
      <el-table-column prop="orderTotalCount" label="订单总数量" align="center" v-if="columns.showColumn('orderTotalCount')"/>
      <el-table-column prop="orderOnlineCount" label="订单上线数量" align="center" v-if="columns.showColumn('orderOnlineCount')"/>
      <el-table-column prop="orderOfflineCount" label="订单下线数量" align="center" v-if="columns.showColumn('orderOfflineCount')"/>
      <el-table-column prop="orderState" label="订单状态" align="center" v-if="columns.showColumn('orderState')">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.orderState" />
        </template>
      </el-table-column>
      <el-table-column prop="creationTime" label="创建时间" :show-overflow-tooltip="true"  v-if="columns.showColumn('creationTime')"/>
      <el-table-column prop="creatorName" label="创建人" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('creatorName')"/>
      <!-- <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['orderinfo:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['orderinfo:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

<!-- 订单导入对话框 -->
<el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        name="file"
        ref="uploadRef"
        :limit="1"
        accept=".xlsx,.xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="upload.open = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
    <!-- 添加或修改订单信息表对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open" >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="产线代号" prop="lineCode">
              <el-input v-model="form.lineCode" placeholder="请输入产线代号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="form.orderType"  placeholder="请选择订单类型">
                <el-option
                  v-for="item in options.orderTypeOptions" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单号" prop="orderCode">
              <el-input v-model="form.orderCode" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="订单物料" prop="orderMaterial">
              <el-input v-model="form.orderMaterial" placeholder="请输入订单物料" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="产品型号" prop="productType">
              <el-select v-model="form.productType"  placeholder="请选择产品型号">
                <el-option
                  v-for="item in options.productTypeOptions" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="上线日期" prop="onlineDate">
              <el-date-picker v-model="form.onlineDate" type="datetime" :teleported="false" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="下线日期" prop="offlineDate">
              <el-date-picker v-model="form.offlineDate" type="datetime" :teleported="false" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="订单排序" prop="orderRank">
              <el-input v-model.number="form.orderRank" placeholder="请输入订单排序" />
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="总数量" prop="orderTotalCount">
              <el-input v-model.number="form.orderTotalCount" placeholder="请输入订单总数量" />
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="上线数量" prop="orderOnlineCount">
              <el-input v-model.number="form.orderOnlineCount" placeholder="请输入订单上线数量" />
            </el-form-item>
          </el-col>
            
          <el-col :lg="12">
            <el-form-item label="下线数量" prop="orderOfflineCount">
              <el-input v-model.number="form.orderOfflineCount" placeholder="请输入订单下线数量" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="orderplan">
import { listOrderInfo,
 addOrderInfo, delOrderInfo, 
 updateOrderInfo,getOrderInfo,
 exportOrderPlan,updateOrderState
 } 
from '@/api/business/orderplan.js'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
  orderCode:''
})

const columns = ref([
  { visible: false, prop: 'id', label: '序号' },
  { visible: true, prop: 'lineCode', label: '产线代号' },
  { visible: true, prop: 'orderType', label: '订单类型' },
  { visible: true, prop: 'orderCode', label: '订单号' },
  { visible: true, prop: 'orderMaterial', label: '订单物料' },
  { visible: true, prop: 'productName', label: '产品名称' },
  { visible: true, prop: 'productType', label: '产品型号' },
  { visible: true, prop: 'onlineDate', label: '上线日期' },
  { visible: false, prop: 'offlineDate', label: '下线日期' },
  { visible: false, prop: 'orderRank', label: '排序' },
  { visible: false, prop: 'orderTotalCount', label: '总数量' },
  { visible: true, prop: 'orderOnlineCount', label: '上线数量' },
  { visible: true, prop: 'orderOfflineCount', label: '下线数量' },
  { visible: true, prop: 'orderState', label: '订单状态' },
  { visible: false, prop: 'creationTime', label: '创建时间' },
  { visible: false, prop: 'creatorName', label: '创建人' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]


function getList(){
  loading.value = true
  listOrderInfo(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)

const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  form: {},
  rules: {
    id: [{ required: true, message: "序号不能为空", trigger: "blur"    , type: "number"  }],
  },
  options: {
    // 订单类型 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
orderTypeOptions: [],
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    lineCode: null,
    orderType: null,
    orderCode: null,
    orderMaterial: null,
    productName: null,
    productType: null,
    onlineDate: null,
    offlineDate: null,
    orderRank: null,
    orderTotalCount: null,
    orderOnlineCount: null,
    orderOfflineCount: null,
    orderState: null,
    creationTime: null,
    creatorName: null,
    isEnabled: null,
    mesPushed: null,
  };
  proxy.resetForm("formRef")
}
//其他按钮
/*** 订单导入参数 */
const upload = reactive({
  // 是否显示弹出层（订单导入）
  open: false,
  // 弹出层标题（订单导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的订单数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/production/orderplan/importData'
})
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 导出按钮操作 */
function handleExport() {
  proxy.$modal
    .confirm('是否确认导出所有订单计划数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      await exportOrderPlan(queryParams.value)
    })
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = '订单导入'
  upload.open = true
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download('/production/orderplan/importTemplate', '订单数据导入模板')
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  const { code, msg, data } = response
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].clearFiles()
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + data.item1 + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  })
  getList()
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}
// 订单数据字典
const statusOptions = ref([])
//字典
proxy.getDicts('order_status').then((response) => {
  statusOptions.value = response.data
})











// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = '添加订单信息表'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getOrderInfo(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改订单信息表'
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {

      if (form.value.id != undefined && opertype.value === 2) {
        updateOrderInfo(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrderInfo(form.value).then((res) => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
      }
    }
  })
}

//订单状态修改
const orderstate=ref(0)
//激活按钮
function handleActivate(){
  opertype.value=4
  orderstate.value=1
   submitOrderActivate()
}
function handleClosed(){
  opertype.value=5
  orderstate.value=2
   submitOrderActivate()
}
//提交激活状态
function submitOrderActivate(){
  const id = ids.value
  proxy
    .$confirm('是否确认修改序号为"' + id + '"的订单状态？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      if(Array.isArray(id) && id.length){
        updateOrderState(id[0],orderstate.value).then(
          (response)=>{
            proxy.$modal.msgSuccess("状态修改成功")
            getList()
          }
        )
      }
    })
}
// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delOrderInfo(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}





handleQuery()
</script>